package com.yidu.view;

import com.yidu.domain.BlogsUser;
import com.yidu.service.BlogsUserService;
import com.yidu.utils.BaseMessage;
import com.yidu.vo.BlogsUserVo;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * <p>@author 陈子睿</p>
 * <p>@Date: 2021/1/20</p>
 * <p>@Time: 21:47</p>
 * <p>@Description: 用户，登录注册</p>
 */
@Controller
@RequestMapping("/user")
public class BlogsUserController {
    @Resource
    BlogsUserService service;

    /**
     * 添加方法
     *
     * @return
     */
    @RequestMapping("/add")
    @ResponseBody
    public BaseMessage add(@RequestParam(value = "photo_") MultipartFile file,
                           BlogsUserVo blogsUserVo,
                           HttpServletRequest request,
                           HttpSession session) {
        System.out.println("进入了增加方法");
        //获取上传的文件名
        String fileName = file.getOriginalFilename();

        //判断文件是否为空
        if (StringUtils.isEmpty(fileName)){
            //如果页面上不选择文件，那么代码会进入这里，photo 还是原来的值
            String photo = request.getParameter("photo");
            blogsUserVo.setPhoto(photo);
        }else {

            //在springMVC中如何取到request,response,session
            int index = fileName.lastIndexOf('.');
            String hz = fileName.substring(index);

            //使用jdk提供的随机字符串
            String newFileName = UUID.randomUUID().toString() + hz;
            //真实路径
            String realPath = request.getServletContext().getRealPath("/upload");
            File target = new File(realPath + "/" + newFileName);
            try {
                //保存文件
                file.transferTo(target);
            } catch (IOException e) {
                e.printStackTrace();
            }
            blogsUserVo.setPhoto("/upload/" + newFileName);
        }
        int rows = service.insertSelective(blogsUserVo);
        //根据返回行数判断增加成功或者失败。
        return rows>0?BaseMessage.succeed():BaseMessage.fail();
    }


}
